<template>
  <div class="dns-load-balancing">
    <h2>DNS 负载均衡</h2>
    <el-tabs type="border-card">
      <el-tab-pane label="负载均衡监控">
        <LoadBalancerMonitoring :nodes="nodes" @update-node-status="updateNodeStatus"/>
      </el-tab-pane>
      <el-tab-pane label="故障模拟">
        <FaultSimulation :nodes="nodes" @simulate-failure="handleSimulateFailure" @simulate-recovery="handleSimulateRecovery"/>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import LoadBalancerMonitoring from './components/LoadBalancerMonitoring.vue';
import FaultSimulation from './components/FaultSimulation.vue';

export default {
  name: "DnsLoadBalancingIndex",
  components: {
    LoadBalancerMonitoring,
    FaultSimulation
  },
  data() {
    return {
      nodes: [
        { nodeId: 1, ip: '192.168.1.1', status: '正常', load: '20%' },
        { nodeId: 2, ip: '192.168.1.2', status: '正常', load: '15%' }
      ],
      intervalIds: []
    };
  },
  methods: {
    updateNodeStatus(nodeId, status) {
      this.nodes = this.nodes.map(node => {
        if (node.nodeId === nodeId) {
          node.status = status;
          if (status === '正常') {
            const intervalId = setInterval(() => {
              const randomLoad = Math.floor(Math.random() * 20 + Math.random() * 10) + '%';
              this.updateNodeLoad(nodeId, randomLoad);
            }, 5000);
            this.intervalIds.push(intervalId);
          } else {
            this.updateNodeLoad(nodeId, '0%');
            this.clearIntervalsForNode(nodeId);
          }
        }
        return node;
      });
    },
    handleSimulateFailure(nodeId) {
      this.updateNodeStatus(nodeId, '故障');
    },
    handleSimulateRecovery(nodeId) {
      this.updateNodeStatus(nodeId, '正常');
    },
    updateNodeLoad(nodeId, load) {
      this.nodes = this.nodes.map(node => {
        if (node.nodeId === nodeId) {
          node.load = load;
        }
        return node;
      });
    },
    clearIntervalsForNode(nodeId) {
      this.intervalIds.forEach((intervalId, index) => {
        clearInterval(intervalId);
        this.intervalIds.splice(index, 1);
      });
    }
  },
  beforeDestroy() {
    this.intervalIds.forEach(intervalId => clearInterval(intervalId));
  }
};
</script>

<style scoped lang="scss">
.dns-load-balancing {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 20px;

  h2 {
    margin-bottom: 20px;
  }
}
</style>
